"""
系统监控和日志模块
"""
import logging
import time
import traceback
from functools import wraps
from django.core.cache import cache
from django.utils import timezone
from django.db import connection
from django.db.models import Count
from collections import defaultdict
import json

logger = logging.getLogger(__name__)


class PerformanceMonitor:
    """性能监控器"""
    
    def __init__(self):
        self.metrics = defaultdict(list)
    
    def record_api_request(self, endpoint, method, duration, status_code, user_id=None):
        """记录API请求性能"""
        metric = {
            'endpoint': endpoint,
            'method': method,
            'duration': duration,
            'status_code': status_code,
            'user_id': user_id,
            'timestamp': timezone.now().isoformat()
        }
        
        # 存储到缓存（最近1000条）
        cache_key = f'api_metrics_{endpoint}_{method}'
        metrics = cache.get(cache_key, [])
        metrics.append(metric)
        if len(metrics) > 1000:
            metrics = metrics[-1000:]
        cache.set(cache_key, metrics, 3600)  # 缓存1小时
        
        # 记录日志
        logger.info(f'API请求: {method} {endpoint} - 耗时: {duration:.3f}s - 状态码: {status_code}')
    
    def record_database_query(self, query, duration):
        """记录数据库查询性能"""
        if duration > 0.1:  # 只记录慢查询（>100ms）
            logger.warning(f'慢查询检测: {query[:200]} - 耗时: {duration:.3f}s')
    
    def get_api_statistics(self, endpoint=None, hours=24):
        """获取API统计信息"""
        # 从缓存获取指标
        if endpoint:
            cache_key = f'api_metrics_{endpoint}_*'
            # 简化实现：返回基本统计
            return {
                'endpoint': endpoint,
                'total_requests': 0,
                'avg_duration': 0,
                'error_rate': 0
            }
        return {}
    
    def get_database_statistics(self):
        """获取数据库统计信息"""
        queries = connection.queries
        if queries:
            total_time = sum(float(q['time']) for q in queries)
            return {
                'total_queries': len(queries),
                'total_time': total_time,
                'avg_time': total_time / len(queries) if queries else 0
            }
        return {
            'total_queries': 0,
            'total_time': 0,
            'avg_time': 0
        }


class ErrorCollector:
    """错误收集器"""
    
    def __init__(self):
        self.errors = []
    
    def record_error(self, error_type, error_message, traceback_str=None, context=None):
        """记录错误"""
        error = {
            'type': error_type,
            'message': str(error_message),
            'traceback': traceback_str,
            'context': context,
            'timestamp': timezone.now().isoformat()
        }
        
        # 存储到缓存（最近100条）
        cache_key = 'system_errors'
        errors = cache.get(cache_key, [])
        errors.append(error)
        if len(errors) > 100:
            errors = errors[-100:]
        cache.set(cache_key, errors, 86400)  # 缓存24小时
        
        # 记录日志
        logger.error(f'系统错误: {error_type} - {error_message}')
        if traceback_str:
            logger.error(f'错误堆栈: {traceback_str}')
    
    def get_recent_errors(self, limit=50):
        """获取最近的错误"""
        errors = cache.get('system_errors', [])
        return errors[-limit:]
    
    def get_error_statistics(self, hours=24):
        """获取错误统计信息"""
        errors = cache.get('system_errors', [])
        error_types = defaultdict(int)
        
        for error in errors:
            error_types[error['type']] += 1
        
        return {
            'total_errors': len(errors),
            'error_types': dict(error_types)
        }


# 全局实例
performance_monitor = PerformanceMonitor()
error_collector = ErrorCollector()


def monitor_performance(func):
    """性能监控装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        try:
            result = func(*args, **kwargs)
            duration = time.time() - start_time
            
            # 记录性能
            endpoint = getattr(func, '__name__', 'unknown')
            performance_monitor.record_api_request(
                endpoint=endpoint,
                method='POST',  # 简化实现
                duration=duration,
                status_code=200
            )
            
            return result
        except Exception as e:
            duration = time.time() - start_time
            
            # 记录错误
            error_collector.record_error(
                error_type=type(e).__name__,
                error_message=str(e),
                traceback_str=traceback.format_exc(),
                context={'function': func.__name__}
            )
            
            raise
    
    return wrapper


def catch_errors(func):
    """错误捕获装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            error_collector.record_error(
                error_type=type(e).__name__,
                error_message=str(e),
                traceback_str=traceback.format_exc(),
                context={'function': func.__name__}
            )
            raise
    
    return wrapper

